﻿using NotaManager;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Serialization;
using WpfClient.Views;

namespace WpfClient
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private Script _script;
        private InfLoadingWindow _loadingWindow;


        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            Application.Current.ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
            loadScript().ContinueWith(task => {

                if (!task.IsCompleted)
                {
                    MessageBox.Show("Initialization error occured! Exiting...");
                    Application.Current.Shutdown();
                }

                CloseSplashAndRunApp();
            }, TaskContinuationOptions.ExecuteSynchronously);
            
            
        }

       
        private void CloseSplashAndRunApp()
        {
            _loadingWindow.Close();
            var notaManager = new DafaultNotaManager();
            var rememberManager = new Remember11Manager();

            var mainWindow = new SimpleViewWindow(new Models.MainViewModel(_script, rememberManager), notaManager);//new MainWindow(new Models.MainViewModel(_script, rememberManager), notaManager);
            this.MainWindow = mainWindow;

            mainWindow.Show();

        }

        async private Task loadScript()
        {
            //try
            {
                var dir = AppDomain.CurrentDomain.BaseDirectory;
                var path = Path.Combine(dir, "base.xml");

                if (!System.IO.File.Exists(path))
                {
                    MessageBox.Show("Script file (base.xml) not found!");
                    Application.Current.Shutdown();
                }
                _loadingWindow = new InfLoadingWindow(new Models.LoadingViewModel("Please wait, script loading..."));
                _loadingWindow.ShowInTaskbar = false;
                _loadingWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                _loadingWindow.Show();

                _script = await loadFromFile(path) ;

                
                //return script;
                
            }
            //catch (Exception e)
            //{
            //    return null;
            //}
        }

        private Task<Script> loadFromFile(string path)
        {
            var task = Task.Run(() =>
            {
                var xml = new XmlSerializer(typeof(Script));
                var script = (Script)xml.Deserialize(System.IO.File.OpenRead(path));
                return script;
            });

            return task;
        }
    }
}
